package controller;

import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by PCG on 2016/5/23.
 */
public class TestSign {

    private static String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2oR3YpD+daZ2gSRaMD5TimBej+cU35vB6/CmGDZ0Vypv44YCk5cTGEMw1HIC23PvGV1MD80WtMUs3+No9snqKT2E27Nusj485afD2zJeA96BGnc8SfpwuPMQNM7p3/3rWCOjNKkntYBcdie45D3WHIJyIkAsTzfTQf6QzkBt9HwIDAQAB";

    private static String openAPIkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCat4+m2txmnoepNDYtoIll9iXf" +
            "KoFLas/bkW4+6Lh9bMnKzs66LavAG6ET4I6/u1ROJStWJVuiEtFRRqm4zhdEkW9a" +
            "qekBAdoozylpqKizgNvQyDKqVjHLQfWuwkLzNKRLDNCoxHxsktOdGITW4VI2DRCD" +
            "tO1VjUJJgUhd6Oq18wIDAQAB";

    public static void main(String[] args) throws Exception{
//        checkSign(pubKey,"","");
        System.out.print(openAPIkey);
    }

    private static final String priKey = "";//私钥

    public static String sign(String data){
        try{
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initSign(privateKey);
            signature.update(data.getBytes("UTF-8"));
            byte[] signbyte = signature.sign();
            return Base64.encodeBase64String(signbyte);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static Boolean checkSign(String pubKey,String data,String signData) throws Exception{
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Signature signature1 = Signature.getInstance("SHA1WithRSA");
        signature1.initVerify(publicKey);
        signature1.update(data.getBytes("UTF-8"));
        return signature1.verify(Base64.decodeBase64(signData));
    }
}
